<template>
  <a-layout>
    <a-tabs v-if="modbus && modbus.property_scans">
      <a-tab-pane tab="属性扫描" key="1" :disabled="!modbus">
        <a-col :span="4" class="withborder">
          <div>
            <span>步骤</span>
          </div>
          <a-space style="margin-top: 10px">
            <a-button icon="file-add" size="small" @click="addStep"></a-button>
            <a-button icon="save" size="small" @click="saveAll"></a-button>
            <a-button icon="delete" size="small" @click="rollback"></a-button>
            <a-button size="small" icon="export" @click="exportStep"></a-button>
            <a-button size="small" icon="import" @click="importStep"></a-button>
          </a-space>
          <a-list :data-source="steps" :style="{ height: lh + 'px' }">
            <a-list-item slot="renderItem" slot-scope="item, index">
              <a-space style="margin-left: 15px">
                <a @click="editStep(index)">第{{ index + 1 }}次扫描</a>
                <a @click="removeStep(index)">删除</a>
                <a @click="editStep(index)">编辑</a>
              </a-space>
            </a-list-item>
          </a-list>
        </a-col>
        <a-col :span="20">
          <a-collapse v-if="currentScan" :activeKey="['1', '2']">
            <a-collapse-panel key="1" header="扫描协议">
              开始位置：<a-input-number
                v-model="currentScan.begin"
              ></a-input-number>
              个数：<a-input-number
                v-model="currentScan.count"
              ></a-input-number>
              功能码:<a-select style="width: 200px" v-model="currentScan.code">
                <a-select-option
                  v-for="item in codeList"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-collapse-panel>
            <a-collapse-panel key="2" header="解析">
              <explain-table
                :mbody="mbody"
                :code="codeList"
                :data="currentExplains"
              ></explain-table>
            </a-collapse-panel>
          </a-collapse>
        </a-col>
      </a-tab-pane>
      <a-tab-pane tab="服务配置" key="2">
        <a-col :span="4" class="withborder">
          <a-space style="margin-top: 16px">
            <a-button icon="save" size="small" @click="saveAll"></a-button>
            <a-button size="small" icon="export" @click="exportStep"></a-button>
            <a-button size="small" icon="import" @click="importStep"></a-button>
          </a-space>
          <service-select-dlg
            :mbody="mbody"
            ref="ServiceDlg"
          ></service-select-dlg>

          <a-list
            :data-source="modbus.service_cmds"
            :style="{ height: lh + 'px', marginTop: '12px' }"
          >
            <a-list-item slot="renderItem" slot-scope="item, index">
              <a-space style="margin-left: 15px">
                {{ index + 1 }}
                <a @click="editService(index)">{{ item.name }}</a>
                <a @click="editService(index)">编辑</a>
              </a-space>
            </a-list-item>
          </a-list>
        </a-col>
        <a-col :span="20">
          <service-display
            v-if="currentService"
            :codeList="codeList"
            :service="currentService"
          ></service-display>
        </a-col>
      </a-tab-pane>
    </a-tabs>
  </a-layout>
</template>
<script>
import ExplainTable from "@/components/modbus/ExplainTable";
import ServiceSelectDlg from "@/components/cfg/ServiceSelectDlg";
import ServiceDisplay from "./ServiceDisplay.vue";
import { de } from "date-fns/locale";

const CODE = [
  { value: "1", title: "读线圈寄存器(1)", label: "读线圈寄存器(1)" },
  { value: "2", title: "读离散输入寄存器(2)", label: "读离散输入寄存器(2)" },
  { value: "3", title: "读保持寄存器(3)", label: "读保持寄存器(3)" },
  { value: "4", title: "读输入寄存器(4)", label: "读输入寄存器(4)" },
  { value: "5", title: "写单个线圈寄存器(5)", label: "写单个线圈寄存器(5)" },
  { value: "6", title: "写单个保持寄存器(6)", label: "写单个保持寄存器(6)" },
  { value: "15", title: "写多个线圈寄存器(15)", label: "写多个线圈寄存器(15)" },
  { value: "16", title: "写多个保持寄存器(16)", label: "写多个保持寄存器(16)" },
];

export default {
  watch: {
    modbus: function (nv) {
      let index = 0;
      if (!nv) {
        this.steps = [];
        //this.services = [];
        //this.modbus = {service_cmds:[]}
        return;
      } else {
        if (nv.property_scans) {
          this.steps = nv.property_scans.map((x) => {
            return { sno: ++index, obj: x };
          });
        } else {
          this.steps = [];
        }

        //this.services = [];
        this.addService();
      }
      if (
        nv &&
        nv.property_scans &&
        nv.property_scans.length > this.currentPropertyIndex
      ) {
        this.currentExplains =
          this.modbus.property_scans[
            this.currentPropertyIndex
          ].property_explains;
      }
      if (
        nv &&
        nv.service_cmds &&
        nv.service_cmds.length > this.currentServiceIndex
      ) {
        this.currentService =
          this.modbus.service_cmds[this.currentServiceIndex];
      }
    },
    deep: true,
    mbody: function (nv) {
      if (nv) {
        this.addService();
      }
    },
  },
  data() {
    return {
      steps: [],
      services: [],
      currentScan: null,
      currentExplains: [],
      codeList: CODE,
      currentPropertyIndex: 0,
      currentService: null,
      currentServiceIndex: 0,
      trueFalse: [
        { label: "是", value: true },
        { label: "否", value: false },
      ],
    };
  },
  props: ["modbus", "mbody"],
  computed: {
    lh() {
      return document.body.clientHeight - 335;
    },
  },
  components: {
    ExplainTable,
    ServiceSelectDlg,
    ServiceDisplay,
  },
  methods: {
    addService() {
      if (this.mbody && this.mbody.services) {
        let self = this;
        if (!self.modbus || !self.modbus.service_cmds) {
          self.modbus.service_cmds = [];
        }

        this.mbody.services.forEach((s) => {
          if (s) {
            let index = self.modbus.service_cmds.findIndex((s2) => {
              return s2.scan_cmd == s.identifier;
            });
            let item = {
              scan_cmd: s.identifier,
              name: s.name,
              obj: s,
              input_params: [],
              scan: {},
              output_params: [],
            };
            if (index == -1) {
              self.modbus.service_cmds.push(item);
            } else {
              self.modbus.service_cmds[index].obj = s;
              self.modbus.service_cmds[index].name = s.name;
            }
          }
        });
      }
    },
    addStep() {
      if (this.modbus) {
        if (!this.modbus.property_scans) {
          this.modbus.property_scans = [];
        }
        this.modbus.property_scans.push({});
        let index = 0;
        this.steps = this.modbus.property_scans.map((x) => {
          return { sno: ++index, obj: x };
        });
      }
    },
    correctItemElementNumver(item, element, isfloat) {
      if (item && element) {
        if (item[element] && item[elment] != 0 && item[element] != '0') {
          if (item[element] == "") {
            delete item[element];
          } else if (typeof item[element] == "string") {
            if (!isfloat) {
              item[element] = parseInt(item[element]);
            } else {
              item[element] = parseFloat(item[element]);
            }
          }
        } else {
          delete item[element];
        }
      }
    },
    correctItem(item) {
      if (item) {
        this.correctItemElementNumver(item, "count");
        this.correctItemElementNumver(item, "begin");
        this.correctItemElementNumver(item, "number", true);
        this.correctItemElementNumver(item, "additive", true);
        
      }
    },
    correct() {
      if (this.currentScan) {
        this.correctItem(this.currentScan);
        if (this.modbus && this.modbus.property_scans) {
          this.modbus.property_scans.forEach((element) => {
            this.correctItem(element);
            if (element.property_explains) {
              element.property_explains.forEach((e) => {
                this.correctItem(e.modbus_param);
              });
            }
          });
        }
      }
      if (this.currentService) {
        this.currentService.input_params.forEach((e) => {
          this.correctItem(e.param);
        });
        this.currentService.output_params.forEach((e) => {
          this.correctItem(e.param);
        });
      }
    },
    saveAll() {
      this.correct();
      this.$emit("save");
    },
    rollback() {
      this.$emit("rollback");
    },
    removeStep(index) {
      this.modbus.property_scans.splice(index, 1);
      this.steps = this.modbus.property_scans.map((x) => {
        return { sno: ++index, obj: x };
      });
    },
    removeService(index) {
      this.modbus.service_cmds.splice(index, 1);
    },
    editStep(index) {
      this.currentPropertyIndex = index;
      if (!this.modbus.property_scans[index].scand_cmd) {
        this.modbus.property_scans[index].scand_cmd = {};
      }
      if (!this.modbus.property_scans[index].property_explains) {
        this.modbus.property_scans[index].property_explains = [];
      }
      this.currentScan = this.modbus.property_scans[index].scand_cmd;
      this.currentExplains =
        this.modbus.property_scans[index].property_explains;
    },
    editService(index) {
      /*if (!this.modbus.service_cmds[index].output_params) {
        this.modbus.service_cmds[index].output_params = [];
      }*/
      if (
        this.modbus &&
        this.modbus.service_cmds &&
        this.modbus.service_cmds.length > index
      ) {
        this.currentService = this.modbus.service_cmds[index];
        this.currentServiceIndex = index;
      }

      //this.currentService = this.modbus.service_cmds[index].scand_cmd;
      //this.currentService = this.modbus.service_cmds[index];
    },
    exportStep() {
      this.correct();
      this.$emit("export");
    },
    importStep() {
      this.correct();
      this.$emit("importall");
    },
  },
};
</script>
<style scoped>
.withborder {
  border: 1px solid green;
}
</style>